var app = {
        ip: 'xiangsongapp.xiaomafeiteng.com',
        app_host: 'https://xiangsongapp.xiaomafeiteng.com/api/',
        statusBar: {
            initDom: function() {
                var div = document.createElement("div");
                div.id = "statusBar";
                div.style.backgroundColor = '#ffffff';
                document.body.insertBefore(div, document.body.firstElementChild);
            },
            set: function() {
                this.initDom();
                $api.fixStatusBar($api.byId('statusBar'));
            },
            pos: function() {
                this.initDom();
                var id = $api.byId('statusBar');
                $api.fixStatusBar(id);
                return $api.offset(id);
            }
        },
        pos: function(id) {
            return $api.offset($api.byId(id));
        },
        api: {
            config: function(callback) {
                var version = api.getPrefs({
                    sync: true,
                    key: 'setting_version'
                });
                var config = {};
                app.request.post('Common/config', {
                    version: version
                }, {}, function(res) {
                    if (res.code == 200) {
                        if (res.data.update === false) {
                            api.readFile({
                                path: 'fs://setting.json'
                            }, function(ret, err) {
                                if (ret) {
                                    callback(JSON.parse(ret.data));
                                } else {
                                    app.error('读取设置文件失败！' + err.code + err.msg)
                                }
                            });
                        } else {
                            api.setPrefs({
                                key: 'setting_version',
                                value: res.data.version
                            });
                            api.writeFile({
                                path: 'fs://setting.json',
                                data: JSON.stringify(res.data.config)
                            }, function(ret, err) {
                                if (!ret.status) {
                                    app.error('设置写入文件失败！' + err.code + err.msg);
                                }
                            });
                            callback(res.data.config);
                        }
                    } else {
                        app.error(res.message);
                    }
                });
            },
            uploadImg: function(type, callback) {
                api.getPicture({
                    sourceType: 'camera',
                    encodingType: 'jpg',
                    mediaValue: 'pic',
                    destinationType: 'url',
                    allowEdit: true,
                    quality: 50,
                    // targetWidth: 100,
                    // targetHeight: 100,
                    saveToPhotoAlbum: false
                }, function(ret, err) {
                    if (ret) {
                        api.showProgress({
                            title: '正在上传',
                            text: '请稍候...',
                            modal: false
                        });
                        app.request.post('Common/uploadImg', {
                            type: type
                        }, {
                            image: ret.data
                        }, function(res) {
                            if (res.code == 200) {
                                callback(res.data.path, res.data.full_path);
                            } else {
                                app.error(res.message);
                            }
                            api.hideProgress();
                        });
                    } else {
                        app.error(err.msg);
                    }
                });
            }
        },
        loginSuccess: function(res, callback) {
            if (res.code == 200 && res.message == 'success') {
                api.setPrefs({
                    key: 'token',
                    value: res.data.token
                });

                //绑定极光推送别名
                var ajpush = api.require('ajpush');
                if (api.systemType == 'android') {
                    ajpush.init(function(ret) {
                        if (ret && ret.status) {
                            ajpush.getRegistrationId(function(ret) {
                                ajpush.bindAliasAndTags({
                                    alias: 'alias_' + res.data.user.id
                                }, function(ret) {
                                    //var statusCode = ret.statusCode;
                                    //console.log(statusCode);
                                });
                            });
                        }
                    });
                } else {
                    ajpush.getRegistrationId(function(ret) {
                        ajpush.bindAliasAndTags({
                            alias: 'alias_' + res.data.user.id
                        }, function(ret) {
                            //var statusCode = ret.statusCode;
                            //console.log(statusCode);
                        });
                    });
                }

                api.sendEvent({
                    name: 'loginSuccess'
                });

                $api.setStorage('is_login', 1);


                callback(res);
            } else {
                app.error(res.message);
            }
        },
        alipay: function(orderInfo, order, type) {
            var aliPay = api.require('aliPay');
            aliPay.payOrder({
                orderInfo: orderInfo
            }, function(ret, err) {
                if (ret.code == 9000) {
                    if (type == 'city') {
                        app.page({
                            name: 'order_detail0',
                            url: 'order_detail0.html',
                            pageParam: {
                                order: order
                            }
                        });
                    } else {
                        app.page({
                            name: 'order_detail1',
                            url: 'order_detail1.html',
                            pageParam: {
                                order: order
                            }
                        });
                    }

                    api.closeWin();
                } else {
                    if (ret.code == '6001') {
                        app.error('取消支付');
                    } else {
                        app.error('code:' + ret.code);
                    }
                }
            });
        },
        wxpay: function(orderInfo, order, type) {
            var wxPay = api.require('wxPay');
            wxPay.payOrder({
                apiKey: orderInfo.appid,
                orderId: orderInfo.prepayid,
                mchId: orderInfo.partnerid,
                nonceStr: orderInfo.noncestr,
                timeStamp: orderInfo.timestamp,
                package: orderInfo.package,
                sign: orderInfo.sign
            }, function(ret, err) {
                // console.log(JSON.stringify(ret))
                // console.log(JSON.stringify(err))
                if (ret.status) {
                    if (type == 'city') {
                        app.page({
                            name: 'order_detail0',
                            url: 'order_detail0.html',
                            pageParam: {
                                order: order
                            }
                        });
                    } else {
                        app.page({
                            name: 'order_detail1',
                            url: 'order_detail1.html',
                            pageParam: {
                                order: order
                            }
                        });
                    }
                    api.closeWin();
                } else {
                    if (err.code == '-2') {
                        app.error('取消支付');
                    } else {
                        app.error(err.code);
                    }
                }
            });
        },
        page: function(options) {
            if (typeof options.animation == 'undefined') {
                options.animation = {
                    type: "push",
                    subType: "from_right",
                    duration: 300
                }
            }
            if (typeof options.progress == 'undefined') {
                options.progress = {
                    type: 'default',
                    title: '正在加载',
                    text: '请耐心等待'
                }
            }
            api.openWin(options);
        },
        request: {
            headers: function() {
                return {
                    from: 'client',
                    token: api.getPrefs({
                        sync: true,
                        key: 'token'
                    })
                };
            },
            get: function(action, callback, options) {
                options = options || {}

                api.ajax({
                    url: app.app_host + action,
                    method: 'get',
                    headers: app.request.headers(),
                    timeout: 30,
                }, function(res, err) {
                    if (res) {
                        callback(res);
                    } else {
                        app.error(err.msg);
                    }
                });
            },
            post: function(action, values, files, callback, options) {
                options = options || {}
                api.ajax({
                    url: app.app_host + action,
                    method: 'post',
                    headers: app.request.headers(),
                    timeout: 30,
                    data: {
                        values: values,
                        files: files
                    },
                }, function(res, err) {
                    if (res) {
                        if (res.code != 200 && res.message == 'login') {
                            api.sendEvent({
                                name: 'logout'
                            });
                            app.error("请先登录！");
                            return;
                        }
                        callback(res);
                    } else {
                        app.error(err.msg);
                    }
                });
            },
            postArray: function(action, values, files, callback, options) {
                options = options || {}
                var _headers = app.request.headers();
                var headers = {
                    'Content-Type': 'application/json',
                    from: _headers.from,
                    token: _headers.token
                }
                api.ajax({
                    url: app.app_host + action,
                    method: 'post',
                    headers: headers,
                    timeout: 9,
                    data: {
                        body: values,
                        files: files
                    },
                }, function(res, err) {
                    if (res) {
                        if (res.code != 200 && res.message == 'login') {
                            api.sendEvent({
                                name: 'logout'
                            });
                            app.error("请先登录！");
                            return;
                        }
                        callback(res);
                    } else {
                        app.error(err.msg);
                    }
                });
            },
            finish: function(v) {
                v.$nextTick(function() {
                    $api.byId('data-loading').style.display = 'none';
                });
            }
        },
        lbs: {
            map: null,
            init: function(callback) {
                this.map = api.require('bMap');
                if (api.systemType == 'ios') {
                    this.map.initMapSDK(function(ret, err) {
                        if (!ret.status) {
                            app.error("lbs初始化失败！");
                        } else {
                            callback && callback()
                        }
                    });
                } else {
                    callback && callback()
                }
            },
            getLocation: function(callback) {
                this.map.getLocation({
                    accuracy: '10m',
                    autoStop: true,
                    filter: 1
                }, function(ret, err) {
                    if (ret.status) {
                        callback(ret.lon, ret.lat);
                    } else {
                        // console.log(JSON.stringify(err));
                        app.error("定位失败！");
                    }
                });
            },
            getAddress: function(lon, lat, callback) {
                this.map.getNameFromCoords({
                    lon: lon,
                    lat: lat
                }, function(ret, err) {
                    if (ret.status) {
                        callback(ret);
                        api.sendEvent({
                            name: 'locationSuccess',
                            extra: {
                                lon: lon,
                                lat: lat,
                                ret: ret
                            }
                        });
                    } else {
                        api.confirm({
                            title: '定位失败',
                            msg: '是否重试?',
                            buttons: ['否', '是']
                        }, function(ret, err) {
                            var index = ret.buttonIndex;
                            if (index == 2) {
                                app.lbs.getAddress(lon, lat, callback);
                            }
                        });
                    }
                    api.hideProgress();
                });
            }
        },
        addEventListener: function(name, callback) {
            api.addEventListener({
                name: name
            }, function(ret, err) {
                callback(ret, err);
            });
        },
        removeEventListener: function(name) {
            api.removeEventListener({
                name: name
            });
        },
        toLogin: function() {
            this.page({
                name: "login0",
                url: "login0.html"
            });
            api.sendEvent({
                name: 'logout'
            });
        },
        error: function(msg) {
            // console.log(msg);
            api.toast({
                msg: msg,
                duration: 2000,
                location: 'top'
            });
            api.hideProgress();
        }
    },
    vObj;
